import axios, {
  AxiosRequestHeaders,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
import { useUserStore } from "../stores/userStore";
import router from "../router";

type TAxiosOption = {
  timeout: number;
  baseURL: string;
};

const baseURL = import.meta.env.BACKEND_URL;
const config: TAxiosOption = {
  timeout: 5000,
  baseURL: baseURL,
};

class Http {
  service;
  constructor(config: TAxiosOption) {
    this.service = axios.create(config);

    /* 请求拦截 */
    this.service.interceptors.request.use(
      (config: InternalAxiosRequestConfig) => {
        //(config.headers as AxiosRequestHeaders).Authorization = 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIzIiwicm9sZXMiOiJVU0VSLE1BSU5UQUlORVIiLCJpYXQiOjE3NDMwNjY2MjksImV4cCI6MTc1ODk2NDIyOX0.HG9KJYT6fpfKhn8p0nGS3CW7Nn98Flb3Z0qIQ72NGPc';
        if (useUserStore().tokenGetter) {
          (config.headers as AxiosRequestHeaders).Authorization =
            "Bearer " + useUserStore().tokenGetter;
        } else {
          if (router.currentRoute.value.path !== "/login") {
            router.push("/login");
          }
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    /* 响应拦截 */
    this.service.interceptors.response.use(
      (response: AxiosResponse<any>) => {
        switch (response.data.code) {
          case 200:
            return response.data;
          case 500:
            return response.data;
          case -1:
            return response.data;
          case 99998:
            layer.confirm("会话超时, 请重新登录", {
              icon: 2,
              yes: function () {
                router.push("/login");
                layer.closeAll();
              },
            });
            return response.data;
          default:
            break;
        }
      },
      (error) => {
        return Promise.reject(error);
      }
    );
  }

  /* GET 方法 */
  get<T>(url: string, params?: object, _object = {}): Promise<any> {
    return this.service.get(url, { params, ..._object });
  }
  /* POST 方法 */
  post<T>(url: string, params?: object, _object = {}): Promise<any> {
    return this.service.post(url, params, _object);
  }
  /* PUT 方法 */
  put<T>(url: string, params?: object, _object = {}): Promise<any> {
    return this.service.put(url, params, _object);
  }
  /* DELETE 方法 */
  delete<T>(url: string, params?: any, _object = {}): Promise<any> {
    return this.service.delete(url, { params, ..._object });
  }
}

export default new Http(config);
